<template>
	<div class="home-box">
		<Header @search="search"/>
		<NavCom @navCom="navCom" :navTabs='navTabs' :currentTab='currentTab' v-if="navTabs.length>1"/>
		 <!-- 展示不同的组件 现在是两种 通用 和短视频 -->
		<component  ref="backTop" class="home-content" :is="currentView" :homeData ='homeData' :recDisplayList='recDisplayList' :firstTab ="firstTab" @onLoad='onLoad' @navCom="navCom" :loading='loading' :finished='finished' :loadHotViewList='loadHotViewList'>
			<!--内容区域根据nav bar id 请求当前页面的数据-->
		</component>
		<NavMore :show='showNavCom' @navCom="navCom" :navList='navTabs'></NavMore>
		<van-overlay :show="showMask" @click="showMask = false" />
		<HomeSearchResult v-if="onSearch" :greatViewList='greatViewList' :searchShortVideoList='searchShortVideoList' @navCom="navCom" @loadeMore='loadeMore' :searchFinished='searchFinished'></HomeSearchResult>
    <AnimationActivity  v-if = 'isAniActivity'  :offAnimationNum = 'offAnimationNum'   :animationActivityData = 'animationActivityData' :activityHomeIcon = 'activityHomeIcon' />
		<!-- 全局背景层组件 -->
		<GlobalMask @formChildMsg='formChildData' v-if="isGlobalMask" />
	</div>
</template>

<script>
    import wxApi from "../util/wxApi";
	import Header from './components/headerSearchCom';//搜索组件
	import NavCom from './components/navCom';//头部导航组件
	import NavMore from './components/navMore';//更多屏道
    import HomeCurrent from './components/homeCurrent';//通用组件（直播，视频）
	import ShortVideo from './components/shortVideo';//短视频组件
	import HomeSearchResult from './components/homeSearchResult';//搜索结果页
      import GlobalMask from '@/components/globalMask'; //全局背景层组件
      import AnimationActivity from '@/components/animationActivity.vue'; //活动动画组件
		export default {
		components: {
			Header,
			NavCom,
			NavMore,
			HomeCurrent,
			ShortVideo,
			HomeSearchResult,
      AnimationActivity,
       GlobalMask,//全局背景层组件
		},
		mixins: [wxApi],
		data() {
			return {
				 currentView: HomeCurrent,
				 showNavCom:false,//是否展示更多屏道页面
				 showMask:false,//是否展示蒙层
				 navTabs:[],//tab
				 homeData:[],//首页数据
				 recDisplayList:[],//推荐位展示
				 shortVideoList:[],//短视频数据
				 firstTab:true,//第一个tab下
				 channelId:null,
				 loading:false ,
         finished: false,
				 pageSize:0,
				 loadHotViewList:[],//热门推荐加载更多数据
				 onSearch:false,
				 currentTab:'',//点击更多传tab当前
				 setScrollTop:0,
				 isAniActivity:false,//首页活动组件
				 animationActivityData:[],
				 offAnimationNum:0,
				 greatViewList:[],//搜索 回看视频数据
				 searchShortVideoList:[],//搜索回看短视频数据
				 type:1,//搜索1 视频 2 短视频
				 page:1,//搜索当前页数
				 keyWord:'',//搜索内容
				 searchFinished:false,//pageSize<10加载完成
				 activityHomeIcon:'',//活动后台配置图标
				 shareInfoData: {}, //分享信息
			}
		},
		computed: {
			isLoadIcon() {
				if (this.$store.state.SysOrgInfo.icon) {
				this.wxRegister(this.wxRegCallback);
				return true
				} else {
				return false
				}
			},
			isGlobalMask() { //操作面板外层透明蒙版 显示
				return this.$store.state.globalMask.isShow
			},
		},
		created() {
              this.$store.dispatch("showNav");
			  this.dotNum();
			  this.getHomeInfo();
			  this.getHomeActivityIcon();
			  fun.componentCreated({channle:'zhxyk',isFirstPage:'1'});//isFirstPage  1-跳转首页，0-返回上页，-1:隐藏公用标题，使用三方页面标题，closePage：关闭当前页面
		},
		mounted() {
		　　// 滚动条的获取
		　　  window.addEventListener('scroll', this.handleScroll, true)
         },
		methods: {
      getHomeActivityIcon(){//获取首页活动配置图标
         this.$http.get("/h5live/hzb/activity/topIcon")
           .then(res => {
             if (res.data.code == "000000") {//type  0 默认 1 自定义
                if(res.data.data && res.data.data.type =='1'){
                   this.activityHomeIcon = res.data.data.iconUrl
                }
                fun.getActivityData(0,0,(res)=>{// 0  首页  0  首页id
                   //console.log(res.data.data[3])
                   if(res.data.data[3].length){
                      this.animationActivityData = res.data.data[3];
                      this.isAniActivity = true;
                   }
                })
             }
           })
           .catch(response => {
             console.log(response);
           });
      },
      formChildData(data){
        switch (data.type){
          case 'closeAllPopup':
            this.offAnimationNum++;
            this.$store.dispatch("globalMask", {isShow:false,bgColor:''});
            break;
          default:
            break;
        }
      },
			 handleScroll() {
				 this.setScrollTop = this.$refs.backTop.$refs.childHome.scrollTop
              },

			// 搜索组件数据
			search(data){
				switch (data.type) {
						case 'onHistory'://历史记录/收藏
							this.collectionRecord();
						break;
						case 'onFocus'://聚焦
							this.showMask = true;
						break;
						case 'onBlur'://失去焦点
							this.showMask = false;
						break;
						case 'onSearch': //搜索中
						     this.onSearch = true
							 this.keyWord = data.data
							 this.page = 1;
							 this.greatViewList =[];
							 this.searchShortVideoList = [];
							 this.searchFinished = false;
							this.searchContent()
						break;
						case 'onCancel': //搜索中
						    this.onSearch = false
						break;
						default:
                         break;
						}

			},
			loadeMore(){
              this.page++;
			  this.searchContent();
			},
			// 历史记录
			collectionRecord(){
					this.$router.push({
		             path: `/${this.$channel}/collectionRecord`,
		         });
			},
			//搜索内容
			searchContent(){
				this.$http.get("/h5live/es/video/getEsVideoList?keyWord=" + this.keyWord + "&type=" + this.type + "&page=" + this.page + "&pageSize=" + 10)
					.then(res => {
						let {code,data}=res.data
						if(code=='000000'){
							if(this.type == '1'){ //视频
								this.greatViewList = this.greatViewList.concat(data);
							}else{
                               this.searchShortVideoList = this.searchShortVideoList.concat(data);
							}
							if(data.length<10){
								this.searchFinished = true; //无加载更多
							}
						}


					})
					.catch(response => {
						console.log(response);
					});

			},
			//头部导航组件数据
			navCom(data){
				switch (data.type) {
						case 'active':
						this.currentTab = data.data
						this.firstTab = data.data.id == this.navTabs[0].id// 仅在第一个tab下出现展示位
						this.channelId = data.data.id;
						this.loadHotViewList = [];
						if(data.data.type == '1'){ //类型 0 标准 1 短视频
							this.currentView = ShortVideo
						}else{
							this.pageSize = 0 ;
						    this.finished = false;
							this.homeData = [];
							this.currentView = HomeCurrent
							this.getTabInfo(data.data.id); //获取当前tab下数据
							// this.onLoad();//热门推荐更多数据
						};

						break;
						case 'more':
							this.showNavCom = true
						break;
						case 'close':
							this.showNavCom = false
						break;
						case 'tabChange'://点击tab
						     this.type = data.data; //
							 this.page = 1;
							 this.greatViewList =[];
							 this.searchShortVideoList = [];
							 this.searchFinished = false;
							 this.searchContent();
						break;
						default:
                         break;
						}

			},
			// 获取tab和推荐页数据
			getHomeInfo(){
				this.$http.get("/h5live/channel/home")
					.then(res => {
					   let {data,code} = res.data
					   if(data && code ==='000000'){
						   this.navTabs = data //tab数据
						//    this.homeData = data[0].channelElementDTOList //推荐页数据
						   this.channelId = data[0].id
						   this.getTabInfo(this.channelId);//首页数据
						   //推荐位展示 isRecommend 0 否 1是
						   this.navTabs.map(item=>{
							   if(item.isRecommend){
                                  this.recDisplayList.push(item)
							   }
						   })
					   }
					})
					.catch(response => {
						console.log(response);
					});
			},
             //获取tab页面数据
			getTabInfo(channelId){
				this.$http.get("/h5live/channel/info?channelId=" + channelId)
					.then(res => {
					   let {data,code} = res.data
					   if(data && code ==='000000'){
						   this.homeData = data.channelElementDTOList //推荐页数据
					   }
					})
					.catch(response => {
						console.log(response);
					});

			},
			//精彩视频更多数据
			onLoad(){
				this.pageSize++;
               	this.$http.get("/h5live/channel/channelVideo?channelId=" + this.channelId + "&p=" + this.pageSize)
					.then(res => {
					   let {data,code} = res.data
					   if(data && code ==='000000'){
						    this.loading = false
							this.loadHotViewList =[...this.loadHotViewList,...data]
						   if(data.length < 10){
							   this.finished = true
						   }

					   }
					})
					.catch(response => {
						console.log(response);
					});
			},
			wxRegCallback() {
					let opstion = {
					//link: window.location.origin + '/#' + this.$route.path,
					link: fun.getShareUrl(this.$channel, 'home'),
					title: this.shareInfoData.shareTitle || '【' + this.$store.state.SysOrgInfo.name + '】一起来看直播吧！', // 分享标题
					desc: this.shareInfoData.shareDesc || "精彩直播，尽在" + this.$store.state.SysOrgInfo.name + "手机直播！", //分享描述
					imgUrl: this.shareInfoData.shareIcon || this.$store.state.SysOrgInfo.icon,
					success: function() {
						//alert("分享成功");
					},
					error: function(e) {
						//alert('分享失败:'+JSON.stringify(e))
					}
					};
					this.ShareTimeline(opstion);
      },
				//分享信息
			getWXInfo() {
				this.$http.get("/h5live/getOrgShare")
				.then(res => {
					if (res.data.code == "000000" && res.data.data !== null) {
					this.shareInfoData = res.data.data;
					}
				})
				.catch(response => {
					console.log(response);
				});
			},
			dotNum() { //统计
				let _this = this;
				var argumentData = {
				sessionId: "home_page", //场次id
				streamType: 12, //视频类型：1-预告 2-直播 3-回看 10-全局统计 11-商品点击 12-页面
				actionValue: 1, //行为：1-进入 2-离开 3-点击播放 4-留言 5-点赞 6-关注 7-分享 8-开播 9-关播 10-最高峰值
				playSource: fun.getPlatform(), //微信 app
				url: window.location.href, //当前的url
				};
				_this.$http.post("/h5live/recordData", argumentData, {
					headers: {
					"Content-Type": "application/json"
					}
				})
				.then(
					res => {
					//console.log(res)
					},
					err => {
					console.log(err);
					}
				);
           },

		},
		watch:{
			isLoadIcon(val, oldVal) {},
			channelId(val){
				if(val){
					this.onLoad()
				}
			},
			$route(to,from){
				if(from.path == '/zhxyk/zhxykHome'){
					window.sessionStorage.setItem('position',this.setScrollTop)
				}else if(to.path == '/zhxyk/zhxykHome'){
					this.$store.dispatch("showNav");
					this.$refs.backTop.$refs.childHome.scrollTop = window.sessionStorage.getItem('position')
				}

			}
		}
	}
</script>


<style scoped="scoped">
	.home-box{
		width: 100vw;
		height: 100vh;
		background: white;

	}
	.home-box /deep/ .van-list__finished-text,
	.home-box /deep/ .van-list__error-text,
	.home-box /deep/ .van-list__loading,
	.home-box /deep/ .van-loading__text{
		font-size: 30px;
		width: 100%;

	}
	.home-box /deep/ .van-list__finished-text{
		width: 100%;
		margin-bottom: 30px;
	}
	.home-box /deep/ .van-cell::after{
		border-bottom: none;

	}
	.home-content{
		position: absolute;
		top:174px ;
		width: 100vw;
		height: calc(100vh - 174px);
		padding-bottom: 100px;
		overflow-y: auto;
	}
	.home-box .van-overlay{
		z-index: 2;
		background-color: rgba(0, 0, 0, 0.4);
	}
</style>
